package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * ClassName: UserServiceImpl
 * Package: com.itheima.mp.service.impl
 * Description:
 *
 * @Author zt
 * @Create 2025/9/16 15:25
 * @Version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    /**
     * 扣减余额
     *
     * @param id
     * @param money
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deductBalance(Long id, Integer money) {
        //1.查询用户
        User user = getById(id);
        //2.校验用户状态（反向校验）
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常！");
        }
        //3.校验余额是否充足
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足！");
        }
        //4.扣减余额 update user set balance = balance - ?
        //baseMapper.deductBalance(id, money);

        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, UserStatus.FROZEN)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance())//乐观锁
                .update();
    }

    /**
     * 根据条件查询用户
     *
     * @param name
     * @param status
     * @param minBalance
     * @param maxBalance
     * @return
     */
    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        //ge >= le <= gt > lt <
        //构建复杂查询
        return lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)//ge >= le <= gt > lt <
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();//用list查多个，one查一个，page做分页，count统计数量
    }

    /**
     * 根据id查询用户和地址
     *
     * @param id
     * @return
     */
    @Override
    public UserVO queryUserAndAddressById(Long id) {
        //1.查询用户
        User user = getById(id);
        //健壮性判断
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常");
        }

        //2.查地址
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();

        //3.封装VO
        //3.1转User的PO为VO
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        //3.2转地址VO（条件判断）
        if (CollUtil.isNotEmpty(addresses)) {
            userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVO;
    }

    /**
     * 根据id批量查询
     *
     * @param ids
     * @return
     */
    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        //1.查询用户
        List<User> users = listByIds(ids);
        //健壮性判断
        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }

        //2.查询地址
        //2.1获取用户id集合
        List<Long> userIds = users.stream().map(User::getId).toList();
        //2.2根据用户id查询地址（所有用户的地址）
        List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();

        //2.3转换地址vo
        List<AddressVO> addressVOList = BeanUtil.copyToList(addresses, AddressVO.class);
        //2.4梳理地址集合，分类整理，相同用户的放入一个集合中（key：用户的id，value：用户地址的集合）
        Map<Long, List<AddressVO>> addressVOMap = new HashMap<>(0);
        if (CollUtil.isNotEmpty(addressVOList)) {
            addressVOMap = addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }

        //3.转VO返回
        List<UserVO> list = new ArrayList<>(users.size());  //提前设置好空间大小，可以有效避免临时扩容
        for (User user : users) {
            //3.1转换user的PO为VO
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            list.add(userVO);
            //3.2转换地址vo（难点：想办法找到属于当前用户的地址）
            userVO.setAddresses(addressVOMap.get(user.getId()));
        }

        return list;
    }

    /**
     * 分页查询用户
     *
     * @param query
     * @return
     */
    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery query) {
        String userName = query.getUsername();
        Integer status = query.getStatus();
        //1.构建分页条件
        Page<User> page = query.toMpPageDefaultSortByUpdateTime();

        //2.分页查询
        Page<User> p = lambdaQuery()
                .like(userName != null, User::getUsername, userName)
                .eq(status != null, User::getStatus, status)
                .page(page);
        //3.封装VO结果
        return PageDTO.of(p, user -> {
            //1.拷贝基础属性
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            //2.处理特殊逻辑
            userVO.setUsername(user.getUsername().substring(0, userVO.getUsername().length() - 2) + "**");
            return userVO;
        });
    }
}
